# -*- coding: utf-8 -*-
# controller.py
#
# Handle control of multiple concurrent game states.

#  Copyright (c) 2008, Abigail Baker, Adam Biltcliffe, Martin O'Leary,
#                      Carrie Oliver, Richard Thomas.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#      * Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#      * Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#      * Neither the name(s) of the copyright holders nor the names of its
#        contributors may be used to endorse or promote products derived from
#        this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
#  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import pyglet

import camera
import config
from constants import *
import game
import level_transition
import menu
import mode

class Controller(object):
    """Handles the control of game modes (e.g. menu, game, cutscene).

    Documentation is hard; let's go shopping!
    add_handler
    set_handler
    suspend_handler
    resume_handler
    switch_handler
    remove_handler
    update
    draw
    run"""

    def __init__(self):
        self.suspended_handlers = {}
        self.musicplayer = pyglet.media.Player()
        self.musicplayer.eos_action = pyglet.media.Player.EOS_LOOP
        self._handler = None

    def get_handler(self):
        return self._handler

    def set_handler(self, handler):
        if isinstance(handler, tuple):
            name, args, kwargs = handler
            handler = mode.get_handler(name, *args, **kwargs)
        if self._handler is not None:
            self._handler.disconnect()
            self.window.remove_handlers(self._handler)
            self._handler = None
        if handler is not None:
            self._handler = handler
            self.window.push_handlers(handler)
            handler.connect(self)
    handler = property(get_handler, set_handler)

    def suspend_handler(self):
        if self.handler is not None:
            self.suspended_handlers[type(self.handler).name] = self.handler
            self.handler = None

    def resume_handler(self, name, suspend=True):
        handler = self.suspended_handlers.pop(name)
        self.switch_handler(name, suspend)

    def switch_handler(self, name, *args, **kwargs):
        """Connect a new handler.

        Additional arguments are passed to the mode constructer.

        :Parameters:
            `name` : str
                The name of the mode class to use.
            `suspend` : bool
                Default False. If True, the current mode is suspended rather
                than dropped.

        """

        suspend = kwargs.pop("suspend", False)
        if suspend:
            self.suspend_handler()
        self.handler = (name, args, kwargs)

    def clear_handler(self):
        self.handler = None

    def update(self, dt):
        if self.handler is not None:
            self.handler.update(dt)

    def setup_pyglet(self):
        self.window = pyglet.window.Window(visible=False, caption=WINDOW_CAPTION,
                                           fullscreen=config.fullscreen)
        pyglet.clock.schedule_interval(self.update, 1.0 / UPDATE_RATE)

    def run(self, level_name=None):
        self.setup_pyglet()
        if level_name is None:
            self.switch_handler(config.starting_mode)
        else:
            self.switch_handler("level_transition", level_name)

        self.window.set_visible()
        pyglet.app.run()

